/**
 * 
 */
package controllers;

import models.Product;
import models.ProductLists;
import play.data.Form;
import play.mvc.*;
import views.html.*;

/**
 * @author Jackie
 *
 */
public class Products extends Controller {
	
	private static ProductLists productList = new ProductLists();
	private static final Form<Product> productForm = Form.form(Product.class);
  
	public static Result lists() {
		return ok(lists.render(productList.displayAll()));
	}
	
	public static Result add() {
		return ok(details.render(productForm));
	}
	
	public static Result delete(String productId) {
		Product product = productList.findById(productId);
		if(product == null) {
			return notFound(String.format("Product %s does not exist.", productId));
		}
		productList.remove(product);
		return redirect(routes.Products.lists());
	} 
	
	public static Result show(String productId) {
		Product product = productList.findById(productId);
		return ok(show.render(product));
	}
	
	public static Result edit(String productId) {
		Product product = productList.findById(productId);
		if(product == null) {
			return notFound(String.format("Product %s does not exist.", productId));
		}
		Form<Product> filledForm = productForm.fill(product);
		return ok(details.render(filledForm));
	}
	
	public static Result save() {
		Form<Product> boundForm = productForm.bindFromRequest();
		
		if(boundForm.hasErrors()) {
			flash("error","Please corect the form below.");
			return badRequest(details.render(boundForm));
		} 
		Product product = boundForm.get();
		productList.add(product);
		flash("success", String.format("Successfully added product %s", product.productName));
		return redirect(routes.Products.lists());
	}
}

